﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

namespace BEELab
{
    public partial class EditPresentationElement : System.Web.UI.Page
    {
        /// <summary>
        /// Fill in Variables menu and Presentation Elements menu
        /// </summary>
        private void CreateCustomMenus()
        {
            //if PresentationElement ID is not empty
            if (Request.QueryString["ID"] != null)
            {
                lblHeadline.Text = "<h2 class=\"headline\">Edit Presentation Element</h2>";

                //Gets names of all variables related to current experiment and fill relevant menu
                SqlCommand command = new SqlCommand();
                command.CommandText = "SELECT Name FROM Variables WHERE ProgramID=(SELECT ProgramID FROM Stages WHERE ID=(SELECT StageID FROM PresentationElements WHERE ID=@ID))";
                command.Parameters.Add(new SqlParameter("@ID", int.Parse(Request.QueryString["ID"].ToString())));
                DataTable dt = BEELab.Data.DBHelper.ExecuteQuery(command);

                FillVariablesMenu(dt);

                //Gets names of all Presentation Elements names related to current experiment and fill relevant menu
                command = new SqlCommand();
                command.CommandText = "SELECT PresentationElements.Name FROM PresentationElements WHERE Name!=@PresentationLayer AND StageID=(SELECT StageID FROM PresentationElements WHERE ID=@ID)";
                command.Parameters.Add(new SqlParameter("@ID", int.Parse(Request.QueryString["ID"].ToString())));
                command.Parameters.Add(new SqlParameter("@PresentationLayer", Properties.Settings.Default.PresentationLayer));
                dt = BEELab.Data.DBHelper.ExecuteQuery(command);
                FillPresentationElementsMenu(dt);
            }
            //else if Stage ID is not empty
            else if (Request.QueryString["StageID"] != null)
            {
                //Gets names of all variables related to current experiment and fill relevant menu
                SqlCommand command = new SqlCommand();
                command.CommandText = "SELECT Name FROM Variables WHERE ProgramID=(SELECT ProgramID FROM Stages WHERE ID=@StageID)";
                command.Parameters.Add(new SqlParameter("@StageID", int.Parse(Request.QueryString["StageID"].ToString())));
                DataTable dt = BEELab.Data.DBHelper.ExecuteQuery(command);

                FillVariablesMenu(dt);

                ////Gets names of all Presentation Elements names related to current experiment and fill relevant menu
                command = new SqlCommand();
                command.CommandText = "SELECT Name FROM PresentationElements WHERE StageID=@StageID";
                command.Parameters.Add(new SqlParameter("@StageID", int.Parse(Request.QueryString["StageID"].ToString())));
                dt = BEELab.Data.DBHelper.ExecuteQuery(command);

                FillPresentationElementsMenu(dt);
            }
        }

        /// <summary>
        /// Gets DataTable of all experiment variable names and fill Variables Literal
        /// </summary>
        /// <param name="dt">DataTable of all experiment variable names</param>
        private void FillVariablesMenu(DataTable dt)
        {
            if (dt == null)
                return;

            VariablesLiteral.Text = "";

            foreach (DataRow row in dt.Rows)
            {
                VariablesLiteral.Text += "{text: '" + row["Name"].ToString() + "', onclick: function() {editor.insertContent('" + Properties.Settings.Default.VariablePrefix + row["Name"].ToString() + Properties.Settings.Default.VariableSuffix + "');}},";
            }

            if (Request.QueryString["ID"] != null)
            {
                //VariablesLiteral.Text += "{text: 'Create New Variable', onclick: function() { editor.windowManager.open({ scrollbars: 'false', title: \"Create New Variable\", url: \"EditVariable.aspx?InTinyMCE=true&ProgramID=" + BEELab.Logic.ProgramManagement.StageManagement.PresentationElements.GetProgramID(int.Parse(Request.QueryString["ID"].ToString())) + "\", width: 700, height: 450 }); }}";
            }
            else if (Request.QueryString["StageID"] != null)
            {
                //VariablesLiteral.Text += "{text: 'Create New Variable', onclick: function() { editor.windowManager.open({ scrollbars: 'false', title: \"Create New Variable\", url: \"EditVariable.aspx?InTinyMCE=true&ProgramID=" + BEELab.Logic.ProgramManagement.StageManagement.StageManagement.GetProgramID(int.Parse(Request.QueryString["StageID"].ToString())) + "\", width: 700, height: 450 }); }}";
            }
        }

        /// <summary>
        /// Gets DataTable of all experiment Presentation Elements names and fill Presentation Literal
        /// </summary>
        /// <param name="dt">DataTable of all experiment Presentation Elements names</param>
        private void FillPresentationElementsMenu(DataTable dt)
        {
            if (dt == null)
                return;

            PresentationLiteral.Text = "";

            foreach (DataRow row in dt.Rows)
            {
                PresentationLiteral.Text += "{text: '" + row["Name"].ToString() + "', onclick: function() {editor.insertContent('" + Properties.Settings.Default.PresentationPrefix + row["Name"].ToString() + Properties.Settings.Default.PresentationSuffix + "');}},";
            }
        }

        /// <summary>
        /// Occures on every page load (first time or Post Back).
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["ID"] != null && BEELab.Logic.ProgramManagement.StageManagement.PresentationElements.GetOwnerID(int.Parse(Request.QueryString["ID"].ToString())) != int.Parse(Session["UserID"].ToString()) && (Session["Admin"] == null || (bool)Session["Admin"] == false))
            {
                Response.Redirect("Main.aspx");
            }

            if ((Request.QueryString["ID"] != null && Request.QueryString["ID"].ToString().Equals("") == false) || (Request.QueryString["StageID"] != null && Request.QueryString["StageID"].ToString().Equals("") == false))
            {
                CreateCustomMenus();
                if (!IsPostBack)
                {
                    if (Request.QueryString["ID"] != null)
                    {
                        BEELab.Logic.ProgramManagement.StageManagement.PresentationElements.PresentationElement element = new Logic.ProgramManagement.StageManagement.PresentationElements.PresentationElement(int.Parse(Request.QueryString["ID"].ToString()));
                        TextBox2.Text = element.Content;
                        TextBox1.Text = element.Name;
                        TextBox3.Text = element.Description;

                        string Names = BEELab.Logic.ProgramManagement.StageManagement.PresentationElements.EnumerateElementsEdit(int.Parse(Request.QueryString["ID"].ToString()), "|");
                        if (Names.Length > 0)
                        {
                            RegexValidator2.ValidationExpression = "^(?!" + Names + ").*$";
                        }
                        else
                        {
                            RegexValidator2.ValidationExpression = ".*";
                        }
                    }
                    else
                    {
                        string Names = BEELab.Logic.ProgramManagement.StageManagement.PresentationElements.EnumerateElementsNew(int.Parse(Request.QueryString["StageID"].ToString()), "|");
                        if (Names.Length > 0)
                        {
                            RegexValidator2.ValidationExpression = "^(?!" + Names + ").*$";
                        }
                        else
                        {
                            RegexValidator2.ValidationExpression = ".*";
                        }
                    }
                }
                else
                {
                    literal1.Text = "<script>window.parent.location.reload(); parent.$.fancybox.close(); </script>";
                }
            }
        }

        /// <summary>
        /// Updates element data details or creates new element date if doesn't exist yet
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnContent_Click(object sender, EventArgs e)
        {
            if (Request.QueryString["ID"] != null)
            {
                BEELab.Logic.ProgramManagement.StageManagement.PresentationElements.UpdateElement(int.Parse(Request.QueryString["ID"].ToString()), TextBox1.Text, TextBox3.Text, TextBox2.Text);
            }
            else if (Request.QueryString["StageID"] != null)
            {
                BEELab.Logic.ProgramManagement.StageManagement.PresentationElements.CreateElement(int.Parse(Request.QueryString["StageID"].ToString()), TextBox1.Text, TextBox3.Text, TextBox2.Text);
            }
        }
    }
}